import { defineStore } from 'pinia'
import { ref, computed, onUnmounted } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { listen } from '@tauri-apps/api/event'
import { BandwidthLevel, BandwidthStatus, BandwidthLevelInfo, RealtimeData, SystemInfo, NetworkStats } from '@/types'
import { formatDuration as formatDurationI18n, formatBytes as formatBytesI18n } from '@/utils/format'

export const useBandwidthStore = defineStore('bandwidth', () => {
  // 状态
  const status = ref<BandwidthStatus | null>(null)
  const levels = ref<BandwidthLevel[]>([])
  const levelInfos = ref<Record<BandwidthLevel, BandwidthLevelInfo>>({} as any)
  const isLoading = ref(false)
  const error = ref<string | null>(null)
  
  // 实时数据状态
  const realtimeData = ref<RealtimeData | null>(null)
  const realtimeHistory = ref<RealtimeData[]>([])
  const maxHistorySize = 60 // 保留60个数据点(约1分钟的历史)
  let unlistenRealtime: (() => void) | null = null
  
  // 系统信息状态
  const systemInfo = ref<SystemInfo | null>(null)
  const networkStats = ref<NetworkStats | null>(null)

  // 计算属性
  const isRunning = computed(() => status.value?.is_running ?? false)
  const currentLevel = computed(() => status.value?.level ?? BandwidthLevel.Off)
  const formattedBytesConsumed = computed(() => {
    const bytes = status.value?.bytes_consumed ?? 0
    return formatBytesI18n(bytes)
  })
  const formattedDuration = computed(() => {
    const seconds = status.value?.duration_seconds ?? 0
    return formatDurationI18n(seconds)
  })
  
  // 实时数据计算属性
  const currentSpeed = computed(() => realtimeData.value?.speed_mbps ?? 0)
  const currentSpeedMBps = computed(() => realtimeData.value?.speed_mb_per_sec ?? 0)
  const peakSpeed = computed(() => realtimeData.value?.peak_speed ?? 0)
  const avgSpeed = computed(() => realtimeData.value?.avg_speed ?? 0)
  const activeConnections = computed(() => realtimeData.value?.active_connections ?? 0)
  const formattedCurrentSpeed = computed(() => `${currentSpeed.value.toFixed(2)} Mbps`)
  const formattedSpeedMBps = computed(() => `${currentSpeedMBps.value.toFixed(2)} MB/s`)
  const formattedPeakSpeed = computed(() => `${peakSpeed.value.toFixed(2)} Mbps`)
  const formattedAvgSpeed = computed(() => `${avgSpeed.value.toFixed(2)} Mbps`)
  
  // 图表数据
  const chartData = computed(() => {
    const data = realtimeHistory.value.slice(-30) // 最近30个数据点
    if (data.length === 0) {
      return {
        labels: [],
        datasets: [
          {
            label: '实时速度 (Mbps)',
            data: [],
            borderColor: 'rgb(59, 130, 246)',
            backgroundColor: 'rgba(59, 130, 246, 0.1)',
            tension: 0.1,
            fill: true
          },
          {
            label: '平均速度 (Mbps)',
            data: [],
            borderColor: 'rgb(16, 185, 129)',
            backgroundColor: 'rgba(16, 185, 129, 0.1)',
            tension: 0.1,
            fill: false
          }
        ]
      }
    }
    
    return {
      labels: data.map(item => new Date(item.timestamp).toLocaleTimeString()),
      datasets: [
        {
          label: '实时速度 (Mbps)',
          data: data.map(item => item.speed_mbps),
          borderColor: 'rgb(59, 130, 246)',
          backgroundColor: 'rgba(59, 130, 246, 0.1)',
          tension: 0.1,
          fill: true
        },
        {
          label: '平均速度 (Mbps)',
          data: data.map(item => item.avg_speed),
          borderColor: 'rgb(16, 185, 129)',
          backgroundColor: 'rgba(16, 185, 129, 0.1)',
          tension: 0.1,
          fill: false
        }
      ]
    }
  })

  // 方法
  const startBandwidthConsumption = async (level: BandwidthLevel) => {
    try {
      isLoading.value = true
      error.value = null
      clearRealtimeData() // 清理之前的数据
      await invoke('start_bandwidth_consumption', { level })
      await fetchStatus()
      await startRealtimeListener() // 确保监听器运行
    } catch (err) {
      error.value = err as string
      console.error('启动带宽占用失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  const stopBandwidthConsumption = async () => {
    try {
      isLoading.value = true
      error.value = null
      await invoke('stop_bandwidth_consumption')
      await fetchStatus()
      clearRealtimeData() // 清理实时数据
    } catch (err) {
      error.value = err as string
      console.error('停止带宽占用失败:', err)
    } finally {
      isLoading.value = false
    }
  }

  const fetchStatus = async () => {
    try {
      const result = await invoke('get_bandwidth_status')
      status.value = result as BandwidthStatus
    } catch (err) {
      console.error('获取状态失败:', err)
    }
  }

  const fetchLevels = async () => {
    try {
      const result = await invoke('get_available_bandwidth_levels')
      levels.value = result as BandwidthLevel[]
      
      // 获取每个等级的详细信息
      const infos: Record<BandwidthLevel, BandwidthLevelInfo> = {} as any
      for (const level of levels.value) {
        const info = await invoke('get_bandwidth_level_info', { level })
        infos[level] = info as BandwidthLevelInfo
      }
      levelInfos.value = infos
    } catch (err) {
      console.error('获取等级信息失败:', err)
    }
  }

  // 实时数据监听
  const startRealtimeListener = async () => {
    if (unlistenRealtime) return // 已经在监听
    
    try {
      unlistenRealtime = await listen<RealtimeData>('realtime-bandwidth-data', (event) => {
        const data = event.payload
        realtimeData.value = data
        
        // 添加到历史数据
        realtimeHistory.value.push(data)
        
        // 保持历史数据大小限制
        if (realtimeHistory.value.length > maxHistorySize) {
          realtimeHistory.value = realtimeHistory.value.slice(-maxHistorySize)
        }
      })
      console.log('开始监听实时带宽数据')
    } catch (error) {
      console.error('启动实时数据监听失败:', error)
    }
  }
  
  const stopRealtimeListener = () => {
    if (unlistenRealtime) {
      unlistenRealtime()
      unlistenRealtime = null
      console.log('停止监听实时带宽数据')
    }
  }
  
  const clearRealtimeData = () => {
    realtimeData.value = null
    realtimeHistory.value = []
  }

  // 获取系统信息
  const fetchSystemInfo = async () => {
    try {
      const result = await invoke('get_system_info')
      systemInfo.value = result as SystemInfo
    } catch (err) {
      console.error('获取系统信息失败:', err)
    }
  }

  // 获取网络统计
  const fetchNetworkStats = async () => {
    try {
      const result = await invoke('get_network_stats')
      networkStats.value = result as NetworkStats
    } catch (err) {
      console.error('获取网络统计失败:', err)
    }
  }

  const initialize = async () => {
    await fetchLevels()
    await fetchStatus()
    await fetchSystemInfo()
    await fetchNetworkStats()
    await startRealtimeListener()
    
    // 定时更新系统信息和网络统计
    setInterval(async () => {
      await fetchSystemInfo()
      await fetchNetworkStats()
    }, 5000) // 每5秒更新一次
  }
  
  // 组件卸载时清理监听器
  onUnmounted(() => {
    stopRealtimeListener()
  })

  return {
    // 状态
    status,
    levels,
    levelInfos,
    isLoading,
    error,
    realtimeData,
    realtimeHistory,
    systemInfo,
    networkStats,
    
    // 计算属性
    isRunning,
    currentLevel,
    formattedBytesConsumed,
    formattedDuration,
    currentSpeed,
    currentSpeedMBps,
    peakSpeed,
    avgSpeed,
    activeConnections,
    formattedCurrentSpeed,
    formattedSpeedMBps,
    formattedPeakSpeed,
    formattedAvgSpeed,
    chartData,
    
    // 方法
    startBandwidthConsumption,
    stopBandwidthConsumption,
    fetchStatus,
    fetchLevels,
    fetchSystemInfo,
    fetchNetworkStats,
    initialize,
    startRealtimeListener,
    stopRealtimeListener,
    clearRealtimeData
  }
})

// 工具函数已移动到 @/utils/format.ts 并国际化 